package com.example.demo.spring.ioc.case02;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 类扫描器
 * 用来扫描出一个包中所有的类信息
 *
 * @author: htc
 * @date: Created in 14:40 2019/1/10.
 */
public class ComponentScanner {
    public static HashMap<String, String> getComponentClassName(String packageName) {
        List<String> classes = getClassName(packageName);
        HashMap<String, String> components = new HashMap<String, String>();
        try {
            for (String cl : classes) {
                cl = cl.replace("workspace_java.LearningJava.bin.", "");
                Component component = Class.forName(cl).getAnnotation(Component.class);
                if (component != null) {
                    components.put(component.id(), cl);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return components;
    }

    /**
     * 扫描所有的.class文件
     * @param packageName
     * @return
     */
    public static List<String> getClassName(String packageName) {
        String filePath = ClassLoader.getSystemResource("").getPath() + packageName.replace(".", "\\");
        //获取.class文件列表
        List<String> fileNames = getClassName(filePath, null);
        return fileNames;
    }

    private static List<String> getClassName(String filePath, List<String> className) {
        List<String> myClassName = new ArrayList<String>();
        File file = new File(filePath);
        File[] childFiles = file.listFiles();
        for (File childFile : childFiles) {
            if (childFile.isDirectory()) {
                myClassName.addAll(getClassName(childFile.getPath(), myClassName));
            } else {
                String childFilePath = childFile.getPath();
                childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf("."));
                childFilePath = childFilePath.replace("\\", ".");
                myClassName.add(childFilePath);
            }
        }
        return myClassName;
    }

    public static void main(String[] args) {
        getComponentClassName("");
    }
}
